<?php

/**
 * Date: 2015-09-09
 */

namespace Admin\Controller;

use Think\AjaxPage;
use Think\Page;
use Admin\Logic\UsersLogic;

class UserController extends BaseController {

    public function index() {
        $this->display();
    }

    /**
     * 会员列表
     */
    public function ajaxindex() {
        // 搜索条件
        $condition = array();
        I('mobile') ? $condition['mobile'] = I('mobile') : false;
        I('email') ? $condition['email'] = I('email') : false;
        I('account') ? $condition['account'] = I('account') : false;
        $sort_order = I('order_by', 'user_id') . ' ' . I('sort', 'desc');
        $timegap = I('timegap');
        if (I('timegap')) {
            $gap = explode(' - ', I('timegap'));
            $begin = $gap[0];
            $end = $gap[1];
            $condition['reg_time'] = array('between', array(strtotime($begin), strtotime($end)));
        }
        $model = M('users');
        $count = $model->where($condition)->count();
        $Page = new AjaxPage($count, 10);
        //  搜索条件下 分页赋值
        foreach ($condition as $key => $val) {
            $Page->parameter[$key] = urlencode($val);
        }

        $userList = $model->where($condition)->order($sort_order)->limit($Page->firstRow . ',' . $Page->listRows)->select();
        foreach ($userList as &$v) {
            $grade = M('user_level')->where(array('level_id' => $v['level']))->field('level_name')->find();
            $v['level_name'] = $grade['level_name'];
        }
        $show = $Page->show();
        $this->assign('userList', $userList);
        $this->assign('page', $show); // 赋值分页输出
        $this->display();
    }

    // 导出会员列表
    public function export_user_index() {
        $condition = array();
        I('mobile') ? $condition['mobile'] = I('mobile') : false;
        I('email') ? $condition['email'] = I('email') : false;
        I('account') ? $condition['account'] = I('account') : false;
        $sort_order = I('order_by', 'user_id') . ' ' . I('sort', 'desc');
        $timegap = I('timegap');
        if (I('timegap')) {
            $gap = explode(' - ', I('timegap'));
            $begin = $gap[0];
            $end = $gap[1];
            $condition['reg_time'] = array('between', array(strtotime($begin), strtotime($end)));
        }
        /*$sql = "select * from __PREFIX__users order by user_id desc";
        $orderList = D()->query($sql);*/

        $orderList = M("users")->where($condition)->order($sort_order)->select();
        $strTable = '<table width="500" border="1">';
        $strTable .= '<tr>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:120px;">序号</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:120px;">推荐人id</td>';
        // $strTable .= '<td style="text-align:center;font-size:12px;width:120px;">报单中心</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:120px;">登录账号</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:120px;">呢称</td>';
        // $strTable .= '<td style="text-align:center;font-size:12px;width:120px;">姓名</td>';
        /*$strTable .= '<td style="text-align:center;font-size:12px;width="120px">联系电话</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width="120px">QQ</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width="120px">微信</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width="120px">邮箱</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width="120px">支付宝</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:120px;">报单时间</td>';*/
        $strTable .= '<td style="text-align:center;font-size:12px;width="120px">级别</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width="120px">注册日期</td>';
        $strTable .= '</tr>';
        if (is_array($orderList)) {
            foreach ($orderList as $k => $val) {
                $val['reg_time']=date("Y-m-d H:i",$val['reg_time']);
                $strTable .= '<tr>';
                $strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;' . $val['user_id'] . '</td>';
                $strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;' . $val['first_leader'] . '</td>';
                // $strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;' . $val['zmd_number'] . '</td>';
                $strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;' . $val['account'] . '</td>';
                $strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;' . $val['nickname'] . '</td>';
                // $strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;' . $val['truename'] . '</td>';
                /*$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;' . $val['mobile'] . '</td>';
                $strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;' . $val['qq'] . '</td>';
                $strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;' . $val['weixin'] . '</td>';
                $strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;' . $val['email'] . '</td>';
                $strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;' . $val['zfb'] . '</td>';
                $strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;' . $val['regtime'] . '</td>';*/
                $strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;' . $val['level'] . '</td>';
                $strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;' . $val['reg_time'] . '</td>';
                $strTable .= '</tr>';
            }
        }
        $strTable .='</table>';
        unset($orderList);
        downloadExcel($strTable, '所有会员列表');
        exit();
    }

    /**
     * 会员详细信息查看
     */
    public function detail() {
        $uid = I('get.id');
        $user = D('users')->where(array('user_id' => $uid))->find();
        if (!$user)
            exit($this->error('会员不存在'));
        if (IS_POST) {
            //  会员信息编辑
            $password = I('post.password');
            $password2 = I('post.password2');
            if ($password != '' && $password != $password2) {
                exit($this->error('两次输入密码不同'));
            }
            if ($password == '' && $password2 == '') {
                unset($_POST['password']);
            } else {
                $_POST['password'] = encrypt($_POST['password']);
            }

            $secpwd = I('post.secpwd');
            $secpwd2 = I('post.secpwd2');
            if ($secpwd != '' && $secpwd != $secpwd2) {
                exit($this->error('两次交易密码输入不同'));
            }
            if ($secpwd == '' && $secpwd2 == '') {
                unset($_POST['secpwd']);
            } else {
                $_POST['secpwd'] = encrypt($_POST['secpwd']);
            }

            $row = M('users')->where(array('user_id' => $uid))->save($_POST);
            if ($row)
                exit($this->success('修改成功'));
            exit($this->error('未作内容修改或修改失败'));
        }
        $this->province = M('region')->where(array('parent_id' => 0, 'level' => 1))->select(); //地址 四级联动 获取省
        $this->city = M('region')->where(array('parent_id' => $user['province'], 'level' => 2))->select(); //  获取订单城市
        $this->district = M('region')->where(array('parent_id' => $user['city'], 'level' => 3))->select(); //获取订单地区
        $this->twon = M('region')->where(array('parent_id' => $user['district'], 'level' => 4))->select(); //获取乡镇
        $this->assign('user', $user);
        $this->display();
    }

    public function add_user() {
        if (IS_POST) {
            $data = I('post.');
            $user_obj = new UsersLogic();
            $res = $user_obj->addUser($data);
            if ($res['status'] == 1) {
                $this->success('添加成功', U('User/index'));
                exit;
            } else {
                $this->error('添加失败,' . $res['msg'], U('User/index'));
            }
        }
        $this->display();
    }

    /**
     * 用户收货地址查看
     */
    public function address() {
        $uid = I('get.id');
        $lists = D('user_address')->where(array('user_id' => $uid))->select();
        $regionList = M('Region')->getField('id,name');
        $this->assign('regionList', $regionList);
        $this->assign('lists', $lists);
        $this->display();
    }

    /**
     * 删除会员
     */
    public function delete() {
        $uid = I('get.id');
        $row = M('users')->where(array('user_id' => $uid))->delete();
        if ($row) {
            $this->success('成功删除会员');
        } else {
            $this->error('操作失败');
        }
    }

    /**
     * 账户资金记录
     */
    public function account_log() {
        $user_id = I('get.id');
        //获取类型
        $type = I('get.type');
        //获取记录总数
        $count = M('account_log')->where(array('user_id' => $user_id))->count();
        $page = new Page($count);
        $lists = M('account_log')->where(array('user_id' => $user_id))->order('change_time desc')->limit($page->firstRow . ',' . $page->listRows)->select();

        $this->assign('user_id', $user_id);
        $this->assign('page', $page->show());
        $this->assign('lists', $lists);
        $this->display();
    }

    /**
     * 账户资金调节
     */
    public function account_edit() {
        $user_id = I('get.id');
        if (!$user_id > 0)
            $this->error("参数有误");
        if (IS_POST) {
            //获取操作类型
            if (tpCache('zfuwl.is_u1') == 1) {
                $user_money_act_type = I('post.user_money_act_type');
                $user_money = I('post.user_money');
                $user_money = $user_money_act_type ? $user_money : 0 - $user_money;
            }else{
                $user_money = 0;
            }
            if (tpCache('zfuwl.is_u2') == 1) {
                $zuce_money_act_type = I('post.zuce_money_act_type');
                $zuce_money = I('post.zuce_money');
                $zuce_money = $zuce_money_act_type ? $zuce_money : 0 - $zuce_money;
            }else{
                $zuce_money = 0;
            }
            if (tpCache('zfuwl.is_u3') == 1) {
                $zuce_money_act_type = I('post.zuce_money_act_type');
                $pay_points = I('post.pay_points');
                $pay_points = $zuce_money_act_type ? $pay_points : 0 - $pay_points;
            }else{
                $pay_points =0;
            }
            if (tpCache('zfuwl.is_u4') == 1) {
                $share_points_act_type = I('post.share_points_act_type');
                $share_points = I('post.share_points');
                $share_points = $share_points_act_type ? $share_points : 0 - $share_points;
            }else{
                $share_points = 0;
            }
            if (tpCache('zfuwl.is_u5') == 1) {
                $frozen_money_act_type = I('post.frozen_money_act_type');
                $frozen_money = I('post.frozen_money');
                $frozen_money = $frozen_money_act_type ? $frozen_money : 0 - $frozen_money;
            }else {
                $frozen_money = 0;
            }

            $desc = I('post.desc');
            if (!$desc)
                $this->error("请填写操作说明");
            if (accountLog($user_id, $user_money, $zuce_money,$pay_points,0,$frozen_money,$share_points,0,$desc)) {
                $this->success("操作成功", U("Admin/User/account_log", array('id' => $user_id)));
            } else {
                $this->error("操作失败");
            }
            exit;
        }
        $this->assign('user_id', $user_id);
        $this->display();
    }

    public function recharge() {
        $timegap = I('timegap');
        $nickname = I('nickname');
        $map = array();
        if ($timegap) {
            $gap = explode(' - ', $timegap);
            $begin = $gap[0];
            $end = $gap[1];
            $map['ctime'] = array('between', array(strtotime($begin), strtotime($end)));
        }
        if ($nickname) {
            $map['nickname'] = array('like', "%$nickname%");
        }
        $count = M('recharge')->where($map)->count();
        $page = new Page($count);
        $lists = M('recharge')->where($map)->order('ctime desc')->limit($page->firstRow . ',' . $page->listRows)->select();
        $this->assign('page', $page->show());
        $this->assign('lists', $lists);
        $this->display();
    }

    public function level() {
        $act = I('GET.act', 'add');
        $this->assign('act', $act);
        $level_id = I('GET.level_id');
        $level_info = array();
        if ($level_id) {
            $level_info = D('user_level')->where('level_id=' . $level_id)->find();
            $this->assign('info', $level_info);
        }
        $this->display();
    }

    public function levelList() {
        $Ad = M('user_level');
        $res = $Ad->where('1=1')->order('level_id')->page($_GET['p'] . ',10')->select();
        if ($res) {
            foreach ($res as $val) {
                $list[] = $val;
            }
        }
        $this->assign('list', $list);
        $count = $Ad->where('1=1')->count();
        $Page = new \Think\Page($count, 10);
        $show = $Page->show();
        $this->assign('page', $show);
        $this->display();
    }

    public function levelHandle() {
        $data = I('post.');
        if ($data['act'] == 'add') {
            $r = D('user_level')->add($data);
        }

        if ($data['act'] == 'edit') {
            if (!preg_match('/^[0-9,]{1,100}$/', $_POST['price1_per'])) {
                $this->error('推荐奖格式错误!');
                die;
            }
            if (!preg_match('/^[0-9,]{1,100}$/', $_POST['price3_per'])) {
                $this->error('重消奖格式错误!');
                die;
            }
            if (!preg_match('/^[0-9,]{1,100}$/', $_POST['price5_per'])) {
                $this->error('见点奖格式错误!');
                die;
            }
            $r = D('user_level')->where('level_id=' . $data['level_id'])->save($data);
        }

        if ($data['act'] == 'del') {
            $r = D('user_level')->where('level_id=' . $data['level_id'])->delete();
            if ($r)
                exit(json_encode(1));
        }

        if ($r) {
            $this->success("操作成功", U('Admin/User/levelList'));
        } else {
            $this->error("操作失败", U('Admin/User/levelList'));
        }
    }

    /**
     * 搜索用户名
     */
    public function search_user() {
        $search_key = trim(I('search_key'));
        if (strstr($search_key, '@')) {
            $list = M('users')->where(" email like '%$search_key%' ")->select();
            foreach ($list as $key => $val) {
                echo "<option value='{$val['user_id']}'>{$val['email']}</option>";
            }
        } else {
            $list = M('users')->where(" mobile like '%$search_key%' ")->select();
            foreach ($list as $key => $val) {
                echo "<option value='{$val['user_id']}'>{$val['mobile']}</option>";
            }
        }
        exit;
    }

    /**
     * 分销树状关系
     */
    public function ajax_distribut_tree() {
        $list = M('users')->where("first_leader = 1")->select();
        $this->display();
    }

    /**
     *
     * @time 2016/08/31
     * @author dyr
     * 发送站内信
     */
    public function sendMessage() {
        $user_id_array = I('get.user_id_array');
        $users = array();
        if (!empty($user_id_array)) {
            $users = M('users')->field('user_id,nickname')->where(array('user_id' => array('IN', $user_id_array)))->select();
        }
        $this->assign('users', $users);
        $this->display();
    }

    /**
     * 发送系统消息
     * @author dyr
     * @time  2016/09/01
     */
    public function doSendMessage() {
        $call_back = I('call_back'); //回调方法
        $message = I('post.text'); //内容
        $type = I('post.type', 0); //个体or全体
        $admin_id = session('admin_id');
        $users = I('post.user'); //个体id
        $message = array(
            'admin_id' => $admin_id,
            'message' => $message,
            'category' => 0,
            'send_time' => array('exp', 'NOW()')
        );
        if ($type == 1) {
            //全体用户系统消息
            $message['type'] = 1;
            M('Message')->data($message)->add();
        } else {
            //个体消息
            $message['type'] = 0;
            if (!empty($users)) {
                $create_message_id = M('Message')->data($message)->add();
                foreach ($users as $key) {
                    M('user_message')->data(array('user_id' => $key, 'message_id' => $create_message_id, 'status' => 0, 'category' => 0))->add();
                }
            }
        }
        echo "<script>parent.{$call_back}(1);</script>";
        exit();
    }

    /**
     *
     * @time 2016/09/03
     * @author dyr
     * 发送邮件
     */
    public function sendMail() {
        $user_id_array = I('get.user_id_array');
        $users = array();
        if (!empty($user_id_array)) {
            $user_where = array(
                'user_id' => array('IN', $user_id_array),
                'email' => array('neq', '')
            );
            $users = M('users')->field('user_id,nickname,email')->where($user_where)->select();
        }
        $this->assign('smtp', tpCache('smtp'));
        $this->assign('users', $users);
        $this->display();
    }

    /**
     * 发送邮箱
     * @author dyr
     * @time  2016/09/03
     */
    public function doSendMail() {
        $call_back = I('call_back'); //回调方法
        $message = I('post.text'); //内容
        $title = I('post.title'); //标题
        $users = I('post.user');
        if (!empty($users)) {
            $user_id_array = implode(',', $users);
            $users = M('users')->field('email')->where(array('user_id' => array('IN', $user_id_array)))->select();
            $to = array();
            foreach ($users as $user) {
                if (check_email($user['email'])) {
                    $to[] = $user['email'];
                }
            }
            $res = send_email($to, $title, $message);
            echo "<script>parent.{$call_back}({$res});</script>";
            exit();
        }
    }

     /**
     * 确认充值
     * @author wxd
     * @time  2016/09/03
     */
    public function confirm_cz() {
        $order_id = I('order_id'); 
        $cz_info=M('recharge')->find($order_id);
        $r1=M('recharge')->where(array('order_id' =>$order_id))->save(array('pay_status' =>1));
        accountLog($cz_info['user_id'],'+'.$cz_info['account'],0,0,0,0,0,0,'管理员确认充值');
        if ($r1) {
           $this->success('确认成功');
        }
    }


}
